const request = require('request');
const config = require('../config/config');
const giteeConfig = config.gitee;
const RedisUtil = require("./RedisUtil");

function GiteeToken() {
}

GiteeToken.isExpired = function (expiresIn, createAt) {
    return new Date().getTime() > ((createAt + expiresIn) * 1000)
}

GiteeToken.getAccessToken = async function () {
    const token = await RedisUtil.get(giteeConfig.tokenCacheKey)
    if (token) {
        if (this.isExpired(token.expires_in, token.created_at)) {
            // 刷新token
            return await this.refreshToken(token.refresh_token);
        }
        return token.access_token;
    }

    let requestDataMap = {
        grant_type: 'password',
        username: giteeConfig.username,
        password: giteeConfig.password,
        client_id: giteeConfig.clientId,
        client_secret: giteeConfig.clientSecret,
        scope: giteeConfig.scope,
    }
    let requestData = '';
    Object.keys(requestDataMap).forEach(function (k) {
        requestData = requestData + (k + "=" + encodeURIComponent(requestDataMap[k])) + "&"
    })
    await request({
        url: giteeConfig.tokenUrl,
        method: "POST",
        headers: {
            "content-type": "application/x-www-form-urlencoded",
        },
        body: requestData
    }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            console.log(body)
            const tokenInfo = JSON.parse(body);
            RedisUtil.set(giteeConfig.tokenCacheKey, tokenInfo, parseInt(tokenInfo.expires_in))
            return tokenInfo.access_token;
        } else {
            console.log(error, response)
            return '';
        }
    });
}

GiteeToken.refreshToken = async function (refreshToken) {

    let requestDataMap = {
        grant_type: 'refresh_token',
        refresh_token: refreshToken,
    }
    let requestData = '';
    Object.keys(requestDataMap).forEach(function (k) {
        requestData = requestData + (k + "=" + encodeURIComponent(requestDataMap[k])) + "&"
    })
    await request({
        url: giteeConfig.tokenUrl,
        method: "POST",
        headers: {
            "content-type": "application/x-www-form-urlencoded",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36",
        },
        body: requestData
    }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            console.log(body)
            const tokenInfo = JSON.parse(body);
            tokenInfo.expires_at = new Date().getTime() + (parseInt(tokenInfo.expires_in) * 1000)
            tokenInfo.isExpired = function () {
                return new Date().getTime() > this.expires_at
            }
            RedisUtil.set(giteeConfig.tokenCacheKey, tokenInfo, parseInt(token.expires_in))
            return tokenInfo.access_token;
        } else {
            console.log(error, response.body)
            return '';
        }
    });
}

module.exports = GiteeToken;
